import threading
from datetime import datetime, timedelta

import numpy as np
from flask import Blueprint, request, jsonify, send_from_directory
from flask_cors import CORS
from flask_login import current_user
from module import Crash, Task
from extension import db
from config import Config
import os

data = np.load("./data/points_sent.npy", allow_pickle=True)

print(data)
print(data[1][1])

data_crash_bp = Blueprint('load_data', __name__)


# def trigger_another_endpoint(endpoint):
#     def decorator(func):
#         def wrapper(*args, **kwargs):
#             response = func(*args, **kwargs)
#             threading.Thread(target=call_endpoint, args=(endpoint,)).start()
#             return response
#         return wrapper
#     return decorator
#
# def call_endpoint(endpoint):
#     from app import app
#     with app.test_client() as client:
#         response = client.post(endpoint)
#         print(f"Called endpoint {endpoint}, response status: {response.status_code}")


@data_crash_bp.route('/load_data_from_Algorithm', methods=['POST'])
def load_data_from_Algorithm():
    global region_json
    data = request.get_json()
    time = data.get('time')
    coordinates = data.get('position', [])
    time = datetime.strptime(time, '%Y-%m-%d %H:%M:%S')

    # 处理坐标数据
    processed_data = []
    for coord in coordinates:
        pos = coord[1]
        x, y = pos
        # 这里可以进行一些处理，例如计算距离、转换坐标等
        processed_data.append((x, y))
        new_task = Task(placex=x, placey=y, starttime=time, finished=0)
        db.session.add(new_task)
        db.session.commit()

    region_json = {'processed_data': processed_data}
    result_json = {'processed_data': processed_data}
    new_crash = Crash(time=time, region=region_json, result=result_json)

    db.session.add(new_crash)

    db.session.commit()

    return jsonify(result_json)
